package com.maben.disruptor.manager;

import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import com.maben.disruptor.factory.TestEventFactory;
import com.maben.disruptor.handler.TestEventHandler;
import com.maben.disruptor.handler.TestEventHandler2;
import com.maben.disruptor.model.MessageModel;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.Executors;

/**
 * disruptor 管理者
 */
@Configuration
public class MQManager {

    @Bean("testMessageModelRingBuffer")
    public RingBuffer<MessageModel> testMessageModelRingBuffer() {
        //指定事件工厂
        TestEventFactory factory = new TestEventFactory();

        //指定ringBuffer字节大小，必须为2的N次方（能将求模运算转为位运算提高效率），否则将影响效率
        int bufferSize = 1024 * 256;

        //单线程模式，获取额外的性能
        Disruptor<MessageModel> disruptor = new Disruptor<>(factory, bufferSize, Executors.defaultThreadFactory(),
                ProducerType.SINGLE, new BlockingWaitStrategy());

        //设置事件业务处理器---消费者
        disruptor.handleEventsWith(new TestEventHandler());
        disruptor.handleEventsWith(new TestEventHandler2());

        // 启动disruptor线程
        disruptor.start();

        //获取ringBuffer环，用于接取生产者生产的事件
        return disruptor.getRingBuffer();
    }
}